package reaction

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"

	"mall/common/cachex"
	"mall/common/ctxdatax"
	"mall/common/mqueuex"
	"mall/common/resultx"
	"mall/service/backend/common/utils/pointy"
	"mall/service/forum/api/internal/lib/forumreaction"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/rpc/forumclient"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type RemoveReactionLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	batcher *mqueuex.Batcher
}

func NewRemoveReactionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RemoveReactionLogic {
	l := &RemoveReactionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}

	b := mqueuex.NewBatcher(
		mqueuex.WithSize(batcherSize),
		mqueuex.WithBuffer(batcherBuffer),
		mqueuex.WithWorker(batcherWorker),
		mqueuex.WithInterval(batcherInterval),
	)
	b.Sharding = func(key string) int {
		if i, err := strconv.ParseInt(key, 10, 64); err == nil {
			return int(i) % batcherWorker
		}

		return 0
	}
	b.Do = func(ctx context.Context, val map[string][]any) {
		var msgs []*mqueuex.ForumReactionMessage
		for _, vs := range val {
			for _, v := range vs {
				msgs = append(msgs, v.(*mqueuex.ForumReactionMessage))
			}
		}
		bs, err := json.Marshal(msgs)
		if err != nil {
			logrus.Info(fmt.Sprintf("RemoveReaction Batcher.Do json.Marshal msgs: %v, error: %v", msgs, err))
		} else {
			if err = l.svcCtx.KqClient.Push(string(bs)); err != nil {
				logrus.Info(fmt.Sprintf("RemoveReaction KqClient.Push msgs: %s, error: %v", string(bs), err))
			}
		}
	}
	l.batcher = b
	l.batcher.Start()

	return l
}

func (l *RemoveReactionLogic) RemoveReaction(req *types.RemoveReactionReq) (resp *types.BaseDataInfo, err error) {
	if req.AuthorId == nil && req.TopicId == nil && req.PostId == nil && req.CommentId == nil {
		return nil, resultx.NewErrCode(resultx.FORUM_REACTION_CONTENT_ID_INVALID)
	}

	userId := ctxdatax.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	var redisKey string
	var contentId uint64
	if req.Type != nil { // 指定且为 "upvote"
		switch *req.Type {
		case "upvote":
			if req.CommentId != nil && *req.CommentId > 0 {
				redisKey = cachex.ForumCommentUpvote
				contentId = *req.CommentId

				forumReaction := forumreaction.NewForumReaction(l.ctx, l.svcCtx, redisKey)
				count, err := forumReaction.Undo(strconv.FormatInt(int64(contentId), 10), strconv.FormatInt(int64(userId), 10))
				if err != nil {
					logrus.Info(fmt.Sprintf("RemoveReaction upvote error : %+v ", err))

					return &types.BaseDataInfo{
						Status:  "fail",
						Message: "取消点赞失败",
					}, nil
				}

				if count >= 0 {
					msg := &mqueuex.ForumReactionMessage{
						AuthorId:  req.AuthorId,
						TopicId:   req.TopicId,
						PostId:    req.PostId,
						CommentId: req.CommentId,
						UserId:    userId,
						Type:      redisKey,
						Status:    0,
					}
					if err = l.batcher.Add(strconv.FormatInt(int64(userId), 10), msg); err != nil {
						logrus.Info(fmt.Sprintf("RemoveReaction upvote batcher.Add error : %+v , message : %+v ", err, msg))
					}

					return &types.BaseDataInfo{
						Status:  "ok",
						Message: "取消点赞成功",
						Count:   count,
					}, nil
				}

				logrus.Info(fmt.Sprintf("RemoveReaction upvote failed : %+v ", count))

				return &types.BaseDataInfo{
					Status:  "fail",
					Message: "取消点赞失败",
				}, nil
			}
		}
	} else { // 默认为 "like"
		if req.TopicId != nil && *req.TopicId > 0 {
			if req.PostId != nil && *req.PostId > 0 {
				redisKey = cachex.ForumAnswerLike
				contentId = *req.PostId
			} else {
				redisKey = cachex.ForumQuestionLike
				contentId = *req.TopicId
			}
		} else if req.PostId != nil && *req.PostId > 0 {
			redisKey = cachex.ForumReviewLike
			contentId = *req.PostId
		}
		forumReaction := forumreaction.NewForumReaction(l.ctx, l.svcCtx, redisKey)
		count, err := forumReaction.Undo(strconv.FormatInt(int64(contentId), 10), strconv.FormatInt(int64(userId), 10))
		if err != nil {
			logrus.Info(fmt.Sprintf("RemoveReaction like error : %+v ", err))

			return &types.BaseDataInfo{
				Status:  "fail",
				Message: "取消点赞失败",
			}, nil
		}

		if count >= 0 {
			msg := &mqueuex.ForumReactionMessage{
				AuthorId: req.AuthorId,
				TopicId:  req.TopicId,
				PostId:   req.PostId,
				UserId:   userId,
				Type:     redisKey,
				Status:   0,
			}
			if err = l.batcher.Add(strconv.FormatInt(int64(userId), 10), msg); err != nil {
				logrus.Info(fmt.Sprintf("RemoveReaction like batcher.Add error : %+v , message : %+v ", err, msg))
			}			

			return &types.BaseDataInfo{
				Status:  "ok",
				Message: "取消点赞成功",
				Count:   count,
			}, nil
		}

		logrus.Info(fmt.Sprintf("RemoveReaction like failed : %+v ", count))

		return &types.BaseDataInfo{
			Status:  "fail",
			Message: "取消点赞失败",
		}, nil
	}

	_, err = l.svcCtx.ForumRpc.RemoveReaction(l.ctx, &forumclient.RemoveReactionReq{
		Ids:       []uint64{contentId},
		UpdatedBy: pointy.GetPointer(userId),
	})
	if err != nil {
		return nil, err
	}

	return &types.BaseDataInfo{
		Status:  "ok",
		Message: "删除成功",
	}, nil
}
